import sys
import asyncio
from asyncio import CancelledError

from nonebot.plugin import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from pydantic.tools import T

from ...dao import db_context
from ...model.user import User
from ...dao import user_dao


binding = on_command("绑定", rule=to_me())

@binding.handle()
async def bind_first_handle(bot:Bot,event:Event,state:T_State):
    this_qqid = event.get_user_id()
    state["this_qqid"]=this_qqid
    
    
@binding.got("this_name",prompt="请问你的名字是？")
async def handle_name(bot:Bot,event:Event,state:T_State):
    pass
    
    
@binding.got("this_studentId",prompt="请问你的学号是？")
async def handle_studentId(bot:Bot,event:Event,state:T_State):
    try: 
        this_studentId=int(state["this_studentId"] )
    except ValueError:
        await binding.reject("学号一般是数字，请输入数字！")
    this_qqid = state["this_qqid"]
    old_studentId=await user_dao.search_and_check(this_qqid)
    if old_studentId==-1:
        this_name=state["this_name"]
        this_qqid=state["this_qqid"]
        this_user = User(this_qqid,this_studentId,this_name)
        print(this_qqid)
        await user_dao.insert_user(this_user)
        await binding.finish("恭喜你，绑定成功！！！")
    else:
        await binding.send("此QQ号之前绑定过学号，绑定的学号为{}。".format(old_studentId))

@binding.got("check", prompt="请问您确定要更换绑定的学号吗？请回答是或否。")
async def handle_check(bot: Bot, event: Event, state: T_State):
    check=state["check"]
    if check=="是":
        this_name=state["this_name"]
        this_qqid=state["this_qqid"]
        this_studentId=state["this_studentId"]
        this_user = User(this_qqid,this_studentId,this_name)
        await user_dao.delete_user(this_qqid)
        await user_dao.insert_user(this_user)
        await binding.send("更换学号成功！")
    elif check=="否":
        await binding.send("已取消更换。")


    